import { createdUser, getUserInfo } from "../service/user.service.js";
import { USER_NAME_IS_EXISTS } from "../constant/err.type.js";
import jwt from "jsonwebtoken";
import process from "../config/config.default.js";
const { JWT_SECRET } = process.env;
export async function register(ctx, next) {
  const { userName, passWord } = ctx.request.body;

  try {
    // 操作数据库存储
    const res = await createdUser(userName, passWord);
    ctx.body = {
      code: 200,
      data: {},
      message: "注册成功",
    };
  } catch (error) {
    app.emit("error", USER_NAME_IS_EXISTS, ctx);
  }
}
export async function login(ctx, next) {
  // 获取用户信息
  const { userName } = ctx.request.body;
  // jwt 生成token 返回给前端 记录 id userName 是否是管理员 isAdmin
  try {
    const { passWord, ...userInfo } = await getUserInfo({ userName });
    // 从返回结果中剔除passWord 字段信息

    const token = jwt.sign(userInfo, JWT_SECRET, {
      expiresIn: "1d", // token有效期 1天
    });
    ctx.body = {
      code: 200,
      message: "登录成功",
      data: {
        token,
        userName,
      },
    };
  } catch (error) {}
}
// 获取当前用户信息
export async function currentUser(ctx, next) {
  console.log(ctx.state.user);
  ctx.body = {
    code: 200,
    data: {
      ...ctx.state.user,
      name: ctx.state.user.userName,
      avatar:
        "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
      userid: ctx.state.user.id,
      email: "",
      signature: "信息-嘻嘻",
      title: "交互专家",
      group: "嘻嘻公司－某某某事业群－某某平台部－某某技术部－UED",
      tags: ["很有想法的", "专注设计", "辣~", "大长腿", "川妹子", "海纳百川"],
      notifyCount: 1,
    },
    message: "获取成功",
  };
}
